<template>
  <div class="reportcharts">
    <h2>{{title}}{{showType=='time'?'分时展示':(showType=='distr'?'分布展示':'入店率')}}</h2>
    <div class="con">
      <div class="toolbox">
        <div class="timeoption" v-if="timeSize.list.length>0 &&showType!='distr'">
          <label style="margin-right:10px;">时间间隔</label>
          <div class="timebtn">
            <el-radio
              v-model="timeSize.check"
              :label="item.tag"
              v-for="item in timeSize.list"
              :key="item.tag"
              @change="timegranuChange"
              border
            >{{item.name}}
            </el-radio>
          </div>
        </div>
      </div>
      <div class="kpi">
        <el-checkbox-group class="kpiBox" v-model="kpiCheckType" size="small" @change="kpiTypeChange">
          <el-checkbox-button v-for="item in Kpisvalue" v-if="item.type == 1"
                              :disabled="kpiCheckType.includes('stay') && (item.name == 'enters' || item.name == 'exits') ? true : false"
                              :key="item.id" :label="item.key">{{item.name}}
          </el-checkbox-button>
        </el-checkbox-group>
        <el-button class="kpiMore"  type="primary" size="small" @click="showTransfer = true">更多 <i class="el-icon-share"></i></el-button>
      </div>
      <div class="echardiv">
        <div
          class="repecharts"
          :id="timeId"
        ></div>
      </div>
      <el-dialog title="选择更多指标" :visible.sync="showTransfer" class="sale-charts-dialog"
                 append-to-body style="text-align: center"  @closed="menuClose">
        <el-transfer
          id="transferKPI"
          style="text-align: left; display: inline-block;"
          v-model="KpisKey"
          :props="{
            key: 'key',
            label: 'name'
          }"
          filterable
          :titles="['未显示指标', '已显示指标']"
          :button-texts="['删除', '添加']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
          @change="transferChange"
          :data="all_kpislist">
        </el-transfer>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showTransfer = false" size="small">取 消</el-button>
          <el-button type="primary" @click="confirmRoleTransfer" size="small">保 存</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>
<style lang="scss">
  .reportcharts {
    width: 100%;
    height: 660px;
    background: #fff;
    padding: 35px 10px 20px 35px;
    overflow: hidden;
    > h2 {
      line-height: 1;
      font-weight: 600;
      font-size: 17px;
      letter-spacing: 1px;
    }
    .echardiv{
      width: 100%;
      height: 420px;
    }
    .repecharts {
      width: 100%;
      height: 520px;
    }
    .con {
      position: relative;
      margin-top: 50px;
      .el-tabs {
        overflow: inherit;
        .el-tabs__header {
          width: 85px;
          .el-tabs__item {
            span {
              font-size: 16px;
              i {
                margin-right: 8px;
              }
            }
          }
        }
        .el-tabs__content {
          overflow: inherit;
          .tab-block{
            display: none!important;
          }
        }
      }
      .kpi{
        position: absolute;
        top: -45px;
        right:0;
        margin-right: 60px;
        .kpiBox{
          display: inline-block;
          vertical-align: top;
        }
        .kpiMore{
          display: inline-block;
          vertical-align: top;
        }
      }
      .kpis {
        position: absolute;
        left: 210px;
        top: -45px;
      }
    }
    .toolbox{
      position: absolute;
      right: 0;
      top: -95px;
      .timeoption {
        float: right;
        margin-right: 60px;
        line-height: 48px;
        .on {
          .el-input--suffix {
            .el-input__inner {
              color: #e8eeff;
              background: #545deb;
            }
          }
        }
        label {
          font-size: 14px;
          color:#7f8ba4;
          vertical-align: top;
        }
        .el-select {
          display: inline-block;
          margin-left: 5px;
          width: 72px;
          height: 30px;
          .el-input__inner {
            box-sizing: border-box;
            height: 32px;
            text-align: center;
            padding: 0 18px 0 0;
            width: 100%;
            font-size: 14px;
          }
          .el-input {
            position: relative;
            z-index: 9;

            .el-input__suffix {
              .el-input__suffix-inner {
                line-height: 100%;
                display: inline-block;
              }
              right: 0;
              span {
                .el-select__caret {
                  font-size: 12px;
                  color: #8ba9ff;
                }
              }
            }
          }
        }
        .timebtn {
          float: right;
          display: block;
          height: 100%;
          padding-top: 10px;
          //margin-left: -3px;
          a,
          .el-radio {
            border: 1px solid #dbe1e5;
            border-left: none;
            margin: 0 !important;
            float: left;
            height: 30px;
            line-height: 30px;
            color: #737373;
            font-size: 14px;
            padding: 0 18px;
            cursor: pointer;
            .el-radio__input {
              display: none;
            }
            .el-radio__label {
              padding: 0;
              line-height: 30px;
            }
            &.on,
            &.is-checked {
              color: #e8eeff !important;
              .el-radio__label {
                color: #e8eeff;
              }
              background: #545deb !important;
            }
            &:first-child {
              border-left: 1px solid #dbe1e5;
              border-radius: 5px 0 0 5px;
            }
            &:last-child {
              border-radius: 0 5px 5px 0;
            }
            &:hover {
              background: #ebebeb;
              color: #333;
              opacity: 0.9;
            }
          }
        }
      }
    }
  }
  .sale-charts-dialog{
    #transferKPI{
      .el-transfer-panel{
        width: 200px;
      }
    }
  }
</style>
<script>
  let echarts = require("echarts");
  let moment = require("moment");
  var Echarts = null;
  import reportGlobal from "@/components/global/reportGlobal";//公共配置
  let unit = reportGlobal.unit;
  let colorList = reportGlobal.colorList;
  export default {
    props: {
      title: {
        default: function() {
          return "出入口";
        }
      },
      all_kpislist: {
        default: function() {
          return [];
        }
      },
      show_kpislist:{
        default: function() {
          return [];
        }
      },
      kpisKey:{
        default: function() {
          return [];
        }
      },
      saveKPi:{
        default: function() {
          return {};
        }
      },
      x_data:{
        default: function() {
          return []
        }
      },
      y_name:{
        default: function() {
          return []
        }
      },
      y_data:{
        default: function() {
          return []
        }
      },
      title_text:{
        default: function() {
          return ""
        }
      },
      timeSize:{        //时间粒度选中和列表
        default:function(){
          return {
            list:[],
            check:'',
          }
        }
      },
      showType:{
        default: function() {
          return "time"
        }
      }
    },
    data() {
      return {
        timeId:
          Number(
            Math.random()
            .toString()
            .substr(3, 15) + Date.now()
          ).toString(36) + "Echarts",
        defaultEcharts:{            //默认样式与无数据图片
          title:{
            show:true,
            text:"暂 无 数 据",
            textAlign:'center',
            left:'48%',
            top:'45%',
            textStyle:{
              fontSize:16,
              color:'#b4b6bd',
            }
          },
          grid: {
            x: 70,
            x2: "8%"
          },
          backgroundColor:{
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: '#f5f8fe' // 0% 处的颜色
            }
            ],
            global: false // 缺省为 false
          },

          series: []
        },
        kpiCheckType:[],
        record:'',          //记录指标点击为最后一个值
        showTransfer:false,//显示更多指标模态框
        valueArr:[],
        options:[],
        KpisKey:[],
        Kpisvalue:[],
        recordKPIList:[],//临时保存穿梭框状态
        code: this.$route.query.code,        //通过菜单栏点击传过来的code判断使用的公共参数
      };
    },
    components: {},
    // created() {},
    mounted() {
      setTimeout(() => {
        window.onresize = () => {
          this.loadEchartResize("");
        };
      }, 200);
      //指标改变
      this.$Bus.$on("ArrowClick", w => {
        this.loadEchartResize(w);
      });
      //默认分时
      Echarts = echarts.init(document.getElementById(this.timeId));
      this.loadEchart(this.defaultEcharts);
      setTimeout(() => {
        this.loadEchartResize("");
      }, 200);
    },
    beforeDestroy(){
      this.$Bus.$off('ArrowClick');
      window.onresize=null;
    },
    watch: {
      all_kpislist(val){

      },
      kpisKey(val){
        this.KpisKey = val
        this.recordKPIList = val
      },
      show_kpislist(val){
        this.Kpisvalue = val
        if(val.length){
          this.kpiCheckType = Array.of(val[0].key)
          this.record = val[0].key
          this.$Bus.$emit('echartsKpiCheck', Array.of(val[0].key),true);
        }
      }
    },
    methods: {
      UpData(ishavedata){
        if(ishavedata==false ||this.y_data.length==0){
          this.loadEchart(this.defaultEcharts);
          return ;
        }
        if(this.kpiCheckType.length<1)
        {
          this.defaultEcharts.title.text="请至少选择一个要查看的指标"
          this.loadEchart(this.defaultEcharts);
          return 
        };
        let option={};
        this.t_color = [];
        let isNumShow=this.kpiCheckType.length==1;      //是否显示大数字
        option.legend={
          type: 'scroll',
          orient: "horizontal",
          width:'70%',
          top: "15",
          left:'center',
          itemGap: 20,
        };
        option.title={
          show:true,
          text:this.title_text,
          textAlign:'center',
          left:'50%',
          textStyle:{
            fontSize:14,
            fontWeight:'none',
            color:'#666',
          }
        };
        let max=1;
        for(let item in this.y_data){
          for(let i=0;i<this.y_data[item].length;i++)
          {
            for(let j=0;j<this.y_data[item][i].length;j++)
            {
              max=max<this.y_data[item][i][j]?this.y_data[item][i][j]:max;
            }
          }
         
        }
        max=max.toString().length;
        option.grid={
          left:max>3?(max*10)+5:40,
          right:(max*10)+15,
          top:'100',
          bottom:100,
        };
        option.tooltip={
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          },
          formatter: function(params) {
            //自定义函数修改折线图给数据加单位
            let str = ""; //声明一个变量用来存储数据
            str += "<div>" + params[0].name + "</div>"; //显示日期的函数
            for (let i = 0; i < params.length; i++) {
              //图显示的数据较多时需要循环数据，这样才可以成功的给多条数据添加单位
              str +=
                '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' +
                params[i].color +
                ';"></span>' +
                params[i].seriesName +
                "</span> : <span>" +
                (params[i].seriesName.includes('率')
                  ? params[i].data + "%"
                  : params[i].data) +
                "</br>";
            }
            return str;
          }
        };
        option.color= [];
        option.toolbox={
          right: "0",
          top: "0",
          feature: {
            magicType: {
              show: true,
              type: ["line", "bar"]
            },
            restore: {
              show: true
            },
            saveAsImage: { show: true }
          }
        };
        option.nameLocation="center";
        option.xAxis=[
          {
            type: "category",
            gridIndex: 0,
            axisLabel: {
              rotate: 30
            },
            data:this.x_data
          }
        ];
        option.yAxis=[
          {
            type: "value",
            name: '',
            position: 'left',
            axisLine: {
              lineStyle: {
                color: '#2c69f3'
              }
            }
          }
        ];
        if(this.isPer(this.kpiCheckType)) {
          let max=this.getMaxPer(this.kpiCheckType);
          option.yAxis.push({
            type: "value",
            name: '百分比',
            min: 0,
            max: max,
            position: 'right',
            axisLine: {
              lineStyle: {
                color: '#b72cff'
              }
            },
            splitLine: {
                show: !this.isPer(this.kpiCheckType,true)
            },
            axisLabel: {
                formatter: '{value}%'
            }
          })
        }
        option.series=[];
        option.dataZoom=[
          {
            show: true,
            start: 0,
            end: 100,
            height:30,
          },
          {
            type: 'slider',
            start: 0,
            end: 100,
          },
        ]

        for (let i = 0; i < this.kpiCheckType.length; i++) {
          let dataArr = this.y_data[this.kpiCheckType[i]];//同一种指标的数据数组
          for (let j = 0; j < dataArr.length; j++) {
            let serObj = {
              type: "bar",
              smooth: true,
              color:colorList[this.kpiCheckType[i]],
              barMaxWidth:this.kpiCheckType.length>1?'22px':'27px',
              yAxisIndex:unit[this.kpiCheckType[i]]=='%'?1:0,
              markLine: {
                data: [
                  {
                    type: "average",
                    name: "平均值"
                  }
                ],
              },
              itemStyle: {
                color: {
                  x:0,
                  y:0,
                  x2:0,
                  y2:1,
                  colorStops: [{
                    offset: 0, color: colorList[this.kpiCheckType[i]]  // 0% 处的颜色
                  }, {
                    offset: 1, color:  '#fff'   // 100% 处的颜色
                  }],
                  global: false // 缺省为 false
                },
							  normal: {
  								label: {
  									show: isNumShow, //开启显示
  									position: 'top', //在上方显示
  									textStyle: { //数值样式
  										color: 'black',
                      fontSize: 16,
                      fontWeight:'bold'
  									}
  								}
  							}
						  },
              markPoint: {
                data: [
                  {
                    type: "max",
                    name: "最大值",
                    fontSize:16,
                    fontWeight:'bold'
                  },
                  {
                    type: "min",
                    name: "最小值",
                    fontSize:16,
                    fontWeight:'bold'
                  }
                ],
              },
              lineStyle:{
                  color: {
                      x:0,
                      y:0,
                      x2:0,
                      y2:1,
                      colorStops: [{
                        offset: 0, color: colorList[this.kpiCheckType[i]]  // 0% 处的颜色
                      }, {
                        offset: 1, color:  '#fff'   // 100% 处的颜色
                      }],
                      global: false // 缺省为 false
                  }
              },
              areaStyle: {
                // color: colorList[this.kpiCheckType[i]],
                color: {
                      x:0,
                      y:0,
                      x2:0,
                      y2:1,
                      colorStops: [{
                        offset: 0, color: colorList[this.kpiCheckType[i]]  // 0% 处的颜色
                      }, {
                        offset: 1, color:  '#fff'   // 100% 处的颜色
                      }],
                      global: false // 缺省为 false
                  }

              },
              name: '',
              data: dataArr[j]
            };
            if(unit[[this.kpiCheckType[i]]]=='%')
            {
              serObj.type = 'line';
              serObj.areaStyle={
                  color: {
                      x:0,
                      y:0,
                      x2:0,
                      y2:1,
                      colorStops: [{
                        offset: 0, color: colorList[this.kpiCheckType[i]]  // 0% 处的颜色
                      }, {
                        offset: 1, color:  '#fff'   // 100% 处的颜色
                      }],
                      global: false // 缺省为 false
                  }
              }
            }
            serObj.name = this.y_name[this.kpiCheckType[i]][j];
            option.series.push(serObj);
          }
        }
        this.loadEchart(option);
      },
      loadEchart(option) {
        Echarts.setOption(option, true);
      },
      loadEchartResize(w) {
        let opts;
        if (this.isEmpty(w)) opts = { width: w };
        else {
          let con_w = $(".con").width();
          opts = { width: con_w };
        }
        Echarts.resize(opts);
      },
      isEmpty(obj) {
        if (typeof obj == "undefined" || obj == null || obj == "") {
          return false;
        } else {
          return true;
        }
      },
      //时间粒度点击
      timegranuChange(val) {
        this.$Bus.$emit("Loading", true);
        this.$Bus.$emit("TimegranuChange", val);
      },
      //指标改变
      kpiTypeChange(val){
        // console.log(val);
        if (val.length > 1) {
          this.$Bus.$emit('echartsKpiCheck', this.kpiCheckType);
        } else if (val.length == 1) {
          this.record = val[0];
          this.$Bus.$emit('echartsKpiCheck', this.kpiCheckType);
        } else {
          this.kpiCheckType.push(this.record);
        }
      },
      //指标中是否存在%单位的
      isPer(arr,isfan=false){
        for(let i in arr)
        {
          if(isfan)
          {
            if(unit[arr[i]]!='%')
            {
              return true;
            }
          }
          else{
             if(unit[arr[i]]=='%')
            {
              return true;
            }
          }
          
        }
        return false;
      },
      //得到Max百分比
      getMaxPer(arr){
        let max=50;
        for(let i in arr) {
          if(unit[arr[i]]=='%') {
            for(let j in this.y_data[arr[i]][0]) {
              max=max > this.y_data[arr[i]][0][j] || !(this.y_data[arr[i]][0][j]) ? max : this.y_data[arr[i]][0][j];
            }
          }
        }
        let a=0;
        if(max>50) {
           a = parseInt( Math.ceil(max)% 10);
        }
        return Math.ceil(max)>50?(Math.ceil(max)+(10-a)):50;
      },
      //关闭模态框钩子
      menuClose(){
        //  console.log('more');
        this.KpisKey = this.recordKPIList
      },
      //保存
      confirmRoleTransfer(){
        //先判断选中的指标个数，不能为空
        if(this.KpisKey.length > 8){
          this.$message.warning('指标选择最多不得超过8个！')
        }else if(this.KpisKey.length){
          this.Kpisvalue = this.all_kpislist.filter(x=>{
            return this.KpisKey.includes(x.key)
          })
          this.kpiCheckType = Array.of(this.Kpisvalue[0].key)
          this.$Bus.$emit('Loading', true);
          this.saveKPI()
        }else{
          this.$message.warning('请至少选择一个指标')
        }
      },
      saveKPI(){
        let showKPIList = this.Kpisvalue.map(x=>x.key)

        for(let i in this.all_kpislist){
          this.saveKPi[this.all_kpislist[i].key] = showKPIList.includes(this.all_kpislist[i].key) ? true : false
        }
        let url = '/sys/report_assist_new/set_web_custom_storage'
        let params = {
          w_key: this.code,
          w_value: JSON.stringify(this.saveKPi)
        }
        this.$api.post(url,params)
        .then(data=>{
          if(data){
            this.recordKPIList = showKPIList
            this.showTransfer = false
            this.$Bus.$emit('saveMore', this.kpiCheckType,this.Kpisvalue);
          }
        })
        .catch(err=>{
          this.$message.error('保存指标失败，请重试！')
          this.$Bus.$emit('Loading', false);
        })
      },
      transferChange(){

      }
    },


  };
</script>
